<?php

/**
 * Admin controller handles the ajax requests
 *
 * @access 	public
 * @author      Rob
 * @copyright	ResMania 2009-present all rights reserved.
 * @version	1.0
 * @link	http://docs.resmania.com/index.php/LiveChat_Module
 * @since  	09-2010
 */
class RM_Admin_LiveChatController extends RM_Controller {

    var $_LiveChatUserGroupID = 98;

    /**
     * This function is not used, however it is here to supress errors
     * @deprecated
     * @return null
     */
    function editJsonAction() {
        return array(
            'data' => ''
        );
    }

    /**
     * this lists all new chat requests.
     * the requests are generated from console.js
     * Look for the ajax request listchattersJson
     *
     * @return json
     */
    function listchattersJsonAction() {
        $dao = new RM_LiveChat();
        $total = $dao->fetchAllOpen()->count();
        $rows = $dao->fetchAllOpen()->toArray();

        $json = new stdClass;
        $json->total = $total;
        $json->data = $rows;

        // update the operator heartbeat
        $daoConfig = new RM_LiveChatConfig();
        $daoConfig->updateOperatorStatus(array('operator_heartbeat'=>date("U")));

        return array(
            'data' => $json
        );
    }

    /**
     * accepts a chat request
     *
     * @return json
     */
    function acceptchatJsonAction() {

        $chat_id = $this->_getParam('chat_id');
        $dao = new RM_LiveChat();
        $result = $dao->acceptChat($chat_id);

        // get operator name
        $daoConfig = new RM_LiveChatConfig();
        $operatorInfo = $daoConfig->getOperator()->toArray();


        $chatData['chat_id'] = $this->_getParam('chat_id');
        $chatData['datetime'] = $this->_getParam('timestamp');
        $chatData['operator'] = $operatorInfo[0]['operator_name'] . " Has Joined the Chat";
        $chatData['user'] = "";
        $chatData['sent_operator'] = 0;
        $chatData['sent_user'] = 0;

        // save to db...
        $daoDialogue = new RM_LiveChatDialogue();
        $result = $daoDialogue->insertDialogue($chatData);

        // this function also sends back information for the admin console
        $chatInfo = $dao->fetchAll($chat_id)->toArray();

        $json = new stdClass;
        $json->data = $chatInfo;


        return array(
            'data' => $json,
            'success' => true
        );
    }

    /**
     * closes a chat
     *
     * @return json
     */
    public function closechatJsonAction() {

        $chat_id = $this->_getParam('chat_id');
        $dao = new RM_LiveChat();
        $result = $dao->closeChat($chat_id);

        return array('data' => array(
                'success' => true
        ));
    }

    /**
     * Sends the message to the server
     *
     * @return json
     */
    public function sendmessageJsonAction() {

        $chat_id = $this->_getParam('chat_id');
        $message = $this->_getParam('message');
        $timestamp = $this->_getParam('timestamp');

        // TODO: check message for bad things

        $chatData['chat_id'] = $chat_id;
        $chatData['operator'] = $message;
        $chatData['datetime'] = $timestamp;

        // update the livechat lastupdate row, this is used to prune old messages
        $dao = new RM_LiveChat();
        $dao->updateLastUpdate($chat_id);

        // insert it to the db...
        $daoDialogue = new RM_LiveChatDialogue();
        $result = $daoDialogue->insert($chatData);

        if ($result) {
            return array('data' => array(
                    'success' => true
            ));
        } else {
            return array('data' => array(
                    'success' => false
            ));
        }
    }

    /**
     * gets updates to the the chat conversation.
     * This is the main process that is called by the JS timer process
     * and runs reguarly. This should be lightweight so it is quick and
     * returns only a small amount of data.
     *
     * @return json
     */
    public function dialogueJsonAction() {

        $chat_id = $this->_getParam('chat_id');

        // chat info
        $dao = new RM_LiveChat();
        $chatInfo = $dao->fetchAll($chat_id)->toArray();

        $daoDialogue = new RM_LiveChatDialogue();
        $rows = $daoDialogue->getDialogue($chat_id, true)->toArray();

        // update the sent marker
        foreach ($rows as $row) {
            $daoDialogue->acknowledgeMessage($row['id'], true);
        }

        $json = new stdClass;
        $json->chatInfo = $chatInfo;
        $json->data = $rows;

        // update the admin istyping status
        $adminIsTyping = (int)$this->_getParam('isTyping');
        $dao->setIsTyping($chat_id,true,$adminIsTyping);

        // get if the user is type
        $isTyping = $dao->getIsTyping(false,$chat_id)->toArray();
        $json->isTyping = $isTyping[0]['user_istyping'];

        return array(
            'data' => $json
        );
    }

    /**
     * updates the operator status: online or offline
     *
     * @return json
     */
    public function updateoperatorJsonAction() {

        if ((int)$this->_getParam('online_status')){
            // update the heartbeat to now
            $chatData['operator_heartbeat'] = date("U");
        } else {
            // set offline by expiring the heartbeat
            $chatData['operator_heartbeat'] = date("U")-300;
        }

        $chatData['operator_name'] = $this->_getParam('operator_name');
        $chatData['operator_id'] = $this->_getParam('operator_id');
        $chatData['sid'] = session_id(); // used to track chat origination

        $dao = new RM_LiveChatOperators();
        $result = $dao->updateOperatorStatus($chatData);

        return array('data' => array(
                'success' => true
        ));
    }

    /**
     * gets the operator status: online or offline
     *
     * @return json
     */
    public function getstatusJsonAction() {
        $dao = new RM_LiveChatConfig();
        $rows = $dao->getStatus();

        $json = new stdClass;
        $json->data = $rows;

        return array(
            'data' => $json
        );
    }

    /**
     * gets the saved operator
     *
     * @return json
     */
    public function loggedinuserJsonAction() {

        // get this logged in user
        $user = RM_Reservation_Manager::getInstance()->getUser();

        $json = new stdClass;
        $json->data = array("cms_id"=>$user->id, "first_name"=>$user->first_name);

        return array(
            'data' => $json
        );
    }
    
    /**
     * Get Operators
     * @return JSON
     */
    public function getoperatorsJsonAction(){
        $model = new RM_Users();
        $users = $model->getAll($this->_LiveChatUserGroupID);

        $jsonArray = array();
        foreach ($users as $user){
            $jsonArray[] = array("id"=>$user->id, "username"=>$user->username, "first_name"=>$user->first_name,"last_name"=>$user->last_name);
        }

        $json = new stdClass;
        //$json->total = count($jsonArray);
        $json->data = $jsonArray;

        return array("data"=>$json);
    }

    /**
     * Prune old chat requests that have not been updated for 30 minutes
     *
     * depreciated
     */
    public function pruneJsonAction() {

        $dao = new RM_LiveChat();
        $chat_ids = $dao->prune();
    }

}